#include "Protocol.hpp"
#include "TcpServer.hpp"
#include "Calculate.hpp"
#include "Daemon.hpp"

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>

using namespace Protocol;
using namespace CalculateNs;

std::string HandlerRequest(std::string &inbufferstream, bool *error_code)
{
    *error_code = true;
    // 0. 计算器对象
    Calculate calculte;

    // 1. 构建响应对象
    std::unique_ptr<Factory> factory = std::make_unique<Factory>();
    auto req = factory->BuildRequest();

    // 2. 分析字节流
    std::string total_resp_string;
    std::string message;
    while (Decode(inbufferstream, &message))
    {
        std::cout << message << "---- messge" << std::endl;
        // 一定读取到了完整报文
        // 3. 反序列化
        if (!req->Deserialize(message))
        {
            *error_code = false;
            return std::string();
        }
        // 4. 业务处理了
        auto resp = calculte.Cal(req);
        // 5. 序列化
        std::string send_string;
        resp->Serialize(&send_string);
        // 添加报头
        send_string = Encode(send_string);
        //
        total_resp_string += send_string;
    }
    return total_resp_string;
}

// ./tcpserver port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port " << std::endl;
        return 1;
    }

    uint16_t localport = std::stoi(argv[1]);
    // 守护进程
    // Daemon(false, false);
    std::unique_ptr<TcpServer> tsvr(new TcpServer(localport, HandlerRequest));
    tsvr->Loop();
    return 0;
}